import axios from "axios";
import {getUserInfo} from "@/utils/system";
import {message} from "@/utils/ElmessasgeUtils";
import {appBase_url} from "@/config/common";
import type {Router} from 'vue-router';
// 先建一个api
const api = axios.create({
    baseURL: appBase_url,
    timeout: 25000 // 请求超时时间
});

let router: Router | null = null;

// 导出设置路由的方法
export function initAxiosInterceptors(routerInstance: Router) {
    router = routerInstance;
    setupInterceptors();
}

function setupInterceptors() {
    // 发送请求前拦截
    api.interceptors.request.use(
        config => {

            const loginUserInfo = getUserInfo();
            if (loginUserInfo != null) {
                if (loginUserInfo.token != '') {
                    config.headers.Authorization = loginUserInfo.token;
                }
            }

            return config;

        },
        error => {
            message(error, 'error');
            return Promise.reject(error);
        }
    )

    // 响应前拦截
    api.interceptors.response.use(
        response => {

            if (!(response.data.code === 200 || response.status === 200)) {
                message("msg: " + response.data.msg, 'warning');
                return Promise.reject(response.data.msg);
            } else {

            }

            return response;
        },
        error => {

            if (error.response) {
                // 请求已发出，但服务器响应的状态码不在 2xx 范围内
                if (error.response.status === 403) {
                    message("登陆信息已经过期，请重新登录", 'error');
                    try {
                        if (router) {
                            router.push('/login')
                        } else {
                            message('路由未定义', 'error');
                        }

                    } catch (_error: any) {
                        message(_error.message, 'error');
                    }

                }
            } else {
                message(error.message, 'error');
            }
            return Promise.reject(error);
        }
    )
}


export default api;
